﻿
using System;
using System.Collections.Generic;
using System.Data;
using SMSPanasonic.Data;
using System.Data.SqlClient;
using System.Text.RegularExpressions;

namespace SMSPanasonic.Business
{
    public partial class SmsMoWaiting
    {
    	#region public properties
		public Guid MoGuid { get; set; }
		public string Subs { get; set; }
		public string Message { get; set; }
		public string ShortCode { get; set; }
		public DateTime? ReceivedTime { get; set; }
		public string Status { get; set; }
		public int? OperatorID { get; set; }
		public Guid? SmsInGUID { get; set; }
		public int? CooperateID { get; set; }
        public int? AgencyID { get; set; }
		#endregion

		#region static method
        public static DataTable GetByTop(int top)
        {
            DataTable retTable = new DataTable();
            try
            {
                using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.ConnectionString))
                {
                    conn.Open();
                    using (SqlCommand cmd = new SqlCommand("usp_MoWaiting_Select", conn))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.CommandTimeout = 30;
                        cmd.Parameters.AddWithValue("@Top", top);
                        retTable.Load(cmd.ExecuteReader());
                        return retTable;
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static void Insert(DataTable dtSource)
        {
            try
            {
                DBSQLCommand.BulkCopy("SmsMoWaiting", dtSource);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        
        //Đăng ký bảo hành
        public static DataRow RegisterWarrany(DataRow row, ref DataTable tableWarranyWaiting, ref DataTable tableCusomerPhone, ref DataTable tableSmsStatistic)
        {
            string mo_message = row["Message"].ToString().ToNormalString();
            string mt_message = "";
            Regex reg = new Regex(@"^(?<prefix>pana)\s(?<phone>\d+)\s(?<model>(\w|\d|-|\(|\)|\.)+)\s(?<product>(\w|\d|-|\(|\)|\.)+)$", RegexOptions.IgnoreCase);
            Match match = reg.Match(mo_message);
            string phone = match.Groups["phone"].ToString().ToNormalPhoneNumber();
            string model = match.Groups["model"].ToString().ToUpper();
            string product = match.Groups["product"].ToString().ToUpper();
            pa_AgencyPhone agency = pa_AgencyPhone.GetOne(row["Subs"].ToString());
            if (agency == null)
            {
                mt_message = MessagePattern.GetMessage(eMessagePattern.SODIENTHOAIKHONGDUOCPHEP);
            }
            else if (!OperatorPrefixCode.ValidatePhoneNumber(phone))
            {
                mt_message = MessagePattern.GetMessage(eMessagePattern.SODIENTHOAIKHONGHOPLE);
                SetStatistic(ref tableSmsStatistic, row, agency.AgencyID, eWarrantyType.DK, false);
            }
            else if (!pa_Model.CheckExists(model))
            {
                mt_message = MessagePattern.GetMessage(eMessagePattern.MODELKHONGTONTAI);
                SetStatistic(ref tableSmsStatistic, row, agency.AgencyID, eWarrantyType.DK, false);
            }
            //else if (pa_Warranty.CheckExists(model, product))
            //{
            //    message = MessagePattern.GetMessage(eMessagePattern.MODELSOMAYDATONTAI)
            //                .Replace("(Model)", model).Replace("(SoMay)", product);
            //    SetStatistic(ref tableSmsStatistic, row, agency.AgencyID, "DK", false);
            //}
            else
            {
                mt_message = MessagePattern.GetMessage(eMessagePattern.PHANHOIDUNGCUPHAPDK);
                //Insert dữ liệu vào pa_WarrantyWaiting
                tableWarranyWaiting.Rows.Add(DBNull.Value, model, product, agency.AgencyID, phone, DBNull.Value, DateTime.Now, eWarrantyType.DK, true, true, DateTime.Now, DBNull.Value, eRegisteredFrom.SMS, row["Subs"], DBNull.Value);
                //Insert dữ liệu vào pa_Customer
                if (!tableCusomerPhone.Rows.Contains(phone))
                    tableCusomerPhone.Rows.Add(phone);
                SetStatistic(ref tableSmsStatistic, row, agency.AgencyID, eWarrantyType.DK, true);
            }
            if (agency != null)
                row["AgencyID"] = agency.AgencyID;
            DataRow newRow = MakeBulkTable.MakeSmsMtWaitingTable().NewRow();
            SetDataRow(ref newRow, row, mt_message);
            return newRow;
        }

        //Đăng ký gia hạn bảo hành
        public static DataRow ExtentWarranty(DataRow row, ref DataTable tableWarranyWaiting, ref DataTable tableCusomerPhone, ref DataTable tableSmsStatistic)
        {
            string mo_message = row["Message"].ToString().ToNormalString();
            string mt_message = "";
            Regex reg = new Regex(@"^(?<prefix>pana)\s(?<phone>\d+)\s(?<model>(\w|\d|-|\(|\)|\.)+)\s(?<product>(\w|\d|-|\(|\)|\.)+)\s(?<package>(\w|\d)+)$", RegexOptions.IgnoreCase);
            Match match = reg.Match(mo_message);
            string phone = match.Groups["phone"].ToString().ToNormalPhoneNumber();
            string model = match.Groups["model"].ToString().ToUpper();
            string product = match.Groups["product"].ToString().ToUpper();
            string package = match.Groups["package"].ToString().ToUpper();
            pa_AgencyPhone agency = pa_AgencyPhone.GetOne(row["Subs"].ToString());
            if (agency == null)
            {
                mt_message = MessagePattern.GetMessage(eMessagePattern.SODIENTHOAIKHONGDUOCPHEP);
            }
            else if (!OperatorPrefixCode.ValidatePhoneNumber(phone))
            {
                mt_message = MessagePattern.GetMessage(eMessagePattern.SODIENTHOAIKHONGHOPLE);
                SetStatistic(ref tableSmsStatistic, row, agency.AgencyID, eWarrantyType.GH, false);
            }
            else if (!pa_Model.CheckExists(model))
            {
                mt_message = MessagePattern.GetMessage(eMessagePattern.MODELKHONGTONTAI);
                SetStatistic(ref tableSmsStatistic, row, agency.AgencyID, eWarrantyType.GH, false);
            }
            else if (!pa_WarrantyPackage.CheckExists(package))
            {
                mt_message = MessagePattern.GetMessage(eMessagePattern.GOIGIAHANKHONGTONTAI);
                SetStatistic(ref tableSmsStatistic, row, agency.AgencyID, eWarrantyType.GH, false);
            }
            //else if (!pa_Warranty.CheckExists(model, product))
            //{
            //    message = MessagePattern.GetMessage(eMessagePattern.MODELSOMAYCHUATONTAI)
            //                .Replace("(Model)", model)
            //                .Replace("(SoMay)", product);
            //    SetStatistic(ref tableSmsStatistic, row, agency.AgencyID, "GH", false);
            //}
            else
            {
                mt_message = MessagePattern.GetMessage(eMessagePattern.PHANHOIDUNGCUPHAPDK);
                //Insert dữ liệu vào pa_WarrantyWaiting
                tableWarranyWaiting.Rows.Add(DBNull.Value, model, product, agency.AgencyID, phone, package, DateTime.Now, eWarrantyType.GH, true, true, DateTime.Now, DBNull.Value, eRegisteredFrom.SMS, row["Subs"], DBNull.Value);
                //Insert dữ liệu vào pa_Customer
                if (!tableCusomerPhone.Rows.Contains(phone))
                    tableCusomerPhone.Rows.Add(phone);
                SetStatistic(ref tableSmsStatistic, row, agency.AgencyID, eWarrantyType.GH, true);
            }
            if (agency != null)
                row["AgencyID"] = agency.AgencyID;
            DataRow newRow = MakeBulkTable.MakeSmsMtWaitingTable().NewRow();
            SetDataRow(ref newRow, row, mt_message);
            return newRow;
        }

        public static DataRow PanaSL(DataRow row)
        {
            string mo_message = row["Message"].ToString().ToNormalString();
            string mt_message = "";
            Regex reg1 = new Regex(@"^(?<prefix>pana\ssl)\s(?<month>\d{1,2})", RegexOptions.IgnoreCase);
            Regex reg2 = new Regex(@"^(?<prefix>pana\ssl)\s(?<month>\d{1,2})(\s|\/|\-)(?<year>\d{4})", RegexOptions.IgnoreCase);
            Regex reg3 = new Regex(@"^(?<prefix>pana\ssl)", RegexOptions.IgnoreCase);
            int month = 0, year = 0;
            pa_AgencyPhone agency = pa_AgencyPhone.GetOne(row["Subs"].ToString());
            if (agency == null)
            {
                mt_message = MessagePattern.GetMessage(eMessagePattern.SODIENTHOAIKHONGDUOCPHEP);
            }
            else if (!reg1.IsMatch(mo_message) && !reg2.IsMatch(mo_message) && !reg3.IsMatch(mo_message))
            {
                mt_message = MessagePattern.GetMessage(eMessagePattern.PHANHOISAICUPHAPSL);
            }
            else
            {
                if (reg1.IsMatch(mo_message))
                {
                    Match match = reg1.Match(mo_message);
                    month = Convert.ToInt32(match.Groups["month"].ToString());
                    year = DateTime.Now.Year;
                }
                else if (reg2.IsMatch(mo_message))
                {
                    Match match = reg2.Match(mo_message);
                    month = Convert.ToInt32(match.Groups["month"].ToString());
                    year = Convert.ToInt32(match.Groups["year"].ToString());
                }
                else if (reg3.IsMatch(mo_message))
                {
                    month = DateTime.Now.Month;
                    year = DateTime.Now.Year;
                }        
                if (month < 1 || month > 12 || year < 1990 || year > 9999)
                {
                    mt_message = MessagePattern.GetMessage(eMessagePattern.PHANHOISAICUPHAPSL);
                }
                else
                {
                    pa_SmsStatistic statistic = pa_SmsStatistic.GetOne(agency.AgencyID, month, year);
                    mt_message = MessagePattern.GetMessage(eMessagePattern.PHANHOIDUNGCUPHAPSL);
                    if (statistic != null)
                    {
                        mt_message = mt_message.Replace("(DKBH)", statistic.RegisterCount.ToString())
                                               .Replace("(DKGHBH)", statistic.ExtentCount.ToString())
                                               .Replace("(DKSAI)", statistic.FailCount.ToString());
                    }
                    else
                    {
                        mt_message = mt_message.Replace("(DKBH)", "0")
                                               .Replace("(DKGHBH)", "0")
                                               .Replace("(DKSAI)", "0");
                    }
                }
            }
            if (agency != null)
                row["AgencyID"] = agency.AgencyID;
            DataRow newRow = MakeBulkTable.MakeSmsMtWaitingTable().NewRow();
            SetDataRow(ref newRow, row, mt_message);
            return newRow;
        }

        public static DataRow PanaKT(DataRow row)
        {
            Regex reg = new Regex(@"^(?<prefix>pana\skt)", RegexOptions.IgnoreCase);
            string mo_message = row["Message"].ToString().ToNormalString();
            string mt_message = "";
            if (!reg.IsMatch(mo_message))
            {
                mt_message = MessagePattern.GetMessage(eMessagePattern.PHANHOISAICUPHAPKT);
            }
            else
            {
                foreach (DataRow wRow in pa_WarrantyDetail.GetByCustomerPhone(row["Subs"].ToString().ToNormalPhoneNumber()).Rows)
                {
                    mt_message += Environment.NewLine + wRow["Description"].ToString();
                }
                if (mt_message == "")
                {
                    mt_message = MessagePattern.GetMessage(eMessagePattern.CHUACOSANPHAMBH);
                }
                else
                {
                    mt_message = mt_message.Substring(mt_message.IndexOf(Environment.NewLine) + Environment.NewLine.Length);
                }
            }
            DataRow newRow = MakeBulkTable.MakeSmsMtWaitingTable().NewRow();
            SetDataRow(ref newRow, row, mt_message);
            return newRow;
        }

        public static DataRow PanaTH(DataRow row)
        {
            Regex reg = new Regex(@"^pana\sth\s(?<model>(\w|\d|-|\(|\)|\.)+)\s(?<product>(\w|\d|-|\(|\)|\.)+)", RegexOptions.IgnoreCase);
            string mo_message = row["Message"].ToString().ToNormalString();
            string mt_message = "";
            if (!reg.IsMatch(mo_message))
            {
                mt_message = MessagePattern.GetMessage(eMessagePattern.PHANHOISAICUPHAP);
            }
            else
            {
                Match match = reg.Match(mo_message);
                string model = match.Groups["model"].ToString().ToUpper();
                string product = match.Groups["product"].ToString().ToUpper();
                foreach (DataRow wRow in pa_WarrantyDetail.GetByModelAndProduct(model, product).Rows)
                {
                    mt_message += Environment.NewLine + wRow["Description"].ToString();
                }
                if (mt_message == "")
                {
                    mt_message = MessagePattern.GetMessage(eMessagePattern.MODELSOMAYCHUATONTAI)
                                .Replace("(Model)", model)
                                .Replace("(SoMay)", product);
                }
                else
                {
                    mt_message = mt_message.Substring(mt_message.IndexOf(Environment.NewLine) + Environment.NewLine.Length);
                }

            }
            DataRow newRow = MakeBulkTable.MakeSmsMtWaitingTable().NewRow();
            SetDataRow(ref newRow, row, mt_message);
            return newRow;
        }

        private static void SetDataRow(ref DataRow mtRow, DataRow moRow, string message)
        {
            mtRow["MtGuid"] = Guid.NewGuid();
            mtRow["MoGuid"] = moRow["MoGuid"];
            mtRow["ShortCode"] = moRow["ShortCode"];
            mtRow["DestAddr"] = moRow["Subs"];
            mtRow["OperatorID"] = moRow["OperatorID"];
            mtRow["Message"] = message;
            mtRow["CooperateID"] = moRow["CooperateID"];
            mtRow["Status"] = "PENDING";
            mtRow["SentTime"] = DateTime.Now;
            mtRow["CDRIndicator"] = "FREE";
            mtRow["MTType"] = SmsShortCode.GetMtType(moRow["ShortCode"].ToString());
            mtRow["RetryOnFailReqTimes"] = Properties.Settings.Default.RetryOnFailReqTimes;
            mtRow["RetryOnTimeOutReqTimes"] = Properties.Settings.Default.RetryOnTimeOutReqTimes;
            mtRow["RetryOnFailReqDuration"] = Properties.Settings.Default.RetryOnFailReqDuration;
            mtRow["RetryOnTimeOutReqDuration"] = Properties.Settings.Default.RetryOnTimeOutReqDuration;
            mtRow["AgencyID"] = moRow["AgencyID"];
        }

        private static void SetStatistic(ref DataTable tableSmsStatistic, DataRow rowinput, int agencyID, string type, bool success)
        {
            DateTime receivedTime = ((DateTime)rowinput["ReceivedTime"]).Date;
            DataRow row = tableSmsStatistic.Rows.Find(new object[] { agencyID, receivedTime});
            if (row == null)
            {
                if (type == eWarrantyType.DK)
                {
                    if (success)
                        tableSmsStatistic.Rows.Add(agencyID, receivedTime, 1, 0, 0);
                    else
                        tableSmsStatistic.Rows.Add(agencyID, receivedTime, 0, 0, 1);
                }
                else
                {
                    if (success)
                        tableSmsStatistic.Rows.Add(agencyID, receivedTime, 0, 1, 0);
                    else
                        tableSmsStatistic.Rows.Add(agencyID, receivedTime, 0, 0, 1);
                }
            }
            else
            {
                if (type == eWarrantyType.DK)
                {
                    if (success)
                        row["RegisterCount"] = (int)row["RegisterCount"] + 1;
                    else
                        row["FailCount"] = (int)row["FailCount"] + 1;
                }
                else
                {
                    if (success)
                        row["ExtentCount"] = (int)row["ExtentCount"] + 1;
                    else
                        row["FailCount"] = (int)row["FailCount"] + 1;
                }
            }
        }
		#endregion
	}
}
